package com.example.portal.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.example.portal.model.ReturnVO;
import com.example.portal.model.SecurityUser;
import com.example.portal.pojo.TokenObject;
import com.example.portal.utils.JwtHelper;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@RequestMapping("/auth")
@Controller
public class LoginController {

    @RequestMapping(value = "/login", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public ReturnVO<String> login(@RequestBody SecurityUser user) {
//    public ReturnVO<String> login(@RequestBody String userName) {
//        String userName = user.getUsername();
//        System.out.println("用户名："+ userName);
//        // 1、业务逻辑
//        // 2、返回token
//        TokenObject token = new TokenObject();
//        token.setBase64Secret("2019");
//        token.setClientId(userName);
//        token.setExpiresSecond(new Date().getTime() + 5*60 * 1000);
        String token = JWT.create().withAudience(user.getId())
                .sign(Algorithm.HMAC256(user.getPassword()));
        return new ReturnVO(token);
//        return new ReturnVO(JwtHelper.createJWTByObj(token));
    }

    @RequestMapping(value = "/getSelfUserInfo", method = RequestMethod.GET)
    @ResponseBody

    public ReturnVO<String> getUserInfo(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Object object) throws Exception
    {
        //获得在线的用户
        String token = httpServletRequest.getHeader("user_token");// 从 http 请求头中取出 token
        String userId = "";
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new RuntimeException("401");
        }

        return new ReturnVO(userId);
    }
}
